package stack_queue.stack;

import java.util.NoSuchElementException;

public class Stack<E> {
    private E[] elementData;
    // 当前栈中元素个数
    private int size;
    public Stack() {
        // int[] data = new int[10];
        elementData = (E[]) new Object[10];
    }
    public Stack(int initCap) {
        elementData = (E[]) new Object[initCap];
    }
    // 入栈操作
    public void push(E value) {
        // TODO 扩容操作 size == elementData.length
        elementData[size ++] = value;
    }
    // 出栈操作,返回原先的栈顶元素
    public E pop() {
        if (getSize() == 0) {
            // 当前栈为空
            throw new NoSuchElementException("栈为空!");
        }
        E oldValue = elementData[size - 1];
        size --;
        elementData[size] = null;
        return oldValue;
    }
    // 查看栈顶元素，不出栈
    public E peek() {
        if (getSize() == 0) {
            throw new NoSuchElementException("栈为空!");
        }
        return elementData[size - 1];
    }
    public int getSize() {
        return size;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < size; i++) {
            sb.append(elementData[i]);
            if (i != size - 1) {
                sb.append(",");
            }
        }
        sb.append("] top");
        return sb.toString();
    }
}

